#!/usr/bin/env python3
# -*- coding: utf-8
"""
PDF导入服务
整合PDF处理和知识库存储，提供完整的PDF文档导入功能
"""

import os
from typing import Dict, Any, List
from pathlib import Path
from services.pdf_processor import create_pdf_processor
from services.knowledge_base import create_knowledge_base_service
from utils.logger import emobot_logger

logger = emobot_logger.get_logger()


class PDFImportService:
    """PDF导入服务"""
    
    def __init__(self, chunk_size: int = 1000, chunk_overlap: int = 200):
        """
        初始化PDF导入服务
        
        Args:
            chunk_size: 文本块大小
            chunk_overlap: 文本块重叠大小
        """
        self.pdf_processor = create_pdf_processor(chunk_size, chunk_overlap)
        self.knowledge_base = create_knowledge_base_service()
        logger.info("PDF导入服务初始化完成")
    
    def import_pdf_folder(self, folder_path: str) -> Dict[str, Any]:
        """
        导入文件夹中的所有PDF文件到知识库
        
        Args:
            folder_path: PDF文件夹路径
            
        Returns:
            导入结果
        """
        try:
            logger.info(f"开始导入PDF文件夹: {folder_path}")
            
            # 验证文件夹路径
            if not os.path.exists(folder_path):
                return {
                    "success": False,
                    "error": f"文件夹不存在: {folder_path}"
                }
            
            # 处理PDF文件
            processing_result = self.pdf_processor.process_pdf_folder(folder_path)
            
            if not processing_result.get("all_chunks"):
                return {
                    "success": False,
                    "error": "没有成功处理任何PDF文件",
                    "processed_files": processing_result.get("processed_files", [])
                }
            
            # 存储到知识库
            storage_result = self.knowledge_base.store_pdf_chunks(processing_result["all_chunks"])
            
            if not storage_result.get("success"):
                return {
                    "success": False,
                    "error": f"存储到知识库失败: {storage_result.get('error', '未知错误')}",
                    "processed_files": processing_result.get("processed_files", [])
                }
            
            # 组合结果
            result = {
                "success": True,
                "folder_path": folder_path,
                "total_files": processing_result.get("total_files", 0),
                "successful_files": processing_result.get("successful_files", 0),
                "total_chunks": processing_result.get("total_chunks", 0),
                "stored_chunks": storage_result.get("stored_count", 0),
                "failed_chunks": storage_result.get("failed_count", 0),
                "processed_files": processing_result.get("processed_files", [])
            }
            
            logger.info(f"PDF文件夹导入完成: {result}")
            return result
            
        except Exception as e:
            logger.error(f"导入PDF文件夹失败: {e}")
            return {
                "success": False,
                "error": str(e),
                "folder_path": folder_path
            }
    
    def import_single_pdf(self, pdf_path: str) -> Dict[str, Any]:
        """
        导入单个PDF文件到知识库
        
        Args:
            pdf_path: PDF文件路径
            
        Returns:
            导入结果
        """
        try:
            logger.info(f"开始导入单个PDF文件: {pdf_path}")
            
            # 验证文件路径
            if not os.path.exists(pdf_path):
                return {
                    "success": False,
                    "error": f"文件不存在: {pdf_path}"
                }
            
            if not pdf_path.lower().endswith('.pdf'):
                return {
                    "success": False,
                    "error": f"不是PDF文件: {pdf_path}"
                }
            
            # 提取PDF文本
            extraction_result = self.pdf_processor.extract_text_from_pdf(pdf_path)
            
            if "error" in extraction_result:
                return {
                    "success": False,
                    "error": f"PDF文本提取失败: {extraction_result['error']}"
                }
            
            # 分割文本
            chunks = self.pdf_processor.split_text_into_chunks(
                extraction_result["full_text"], 
                extraction_result
            )
            
            if not chunks:
                return {
                    "success": False,
                    "error": "PDF文本分割后没有生成任何文本块"
                }
            
            # 存储到知识库
            storage_result = self.knowledge_base.store_pdf_chunks(chunks)
            
            if not storage_result.get("success"):
                return {
                    "success": False,
                    "error": f"存储到知识库失败: {storage_result.get('error', '未知错误')}"
                }
            
            result = {
                "success": True,
                "file_path": pdf_path,
                "file_name": extraction_result["file_name"],
                "total_pages": extraction_result["total_pages"],
                "total_characters": extraction_result["total_characters"],
                "total_chunks": len(chunks),
                "stored_chunks": storage_result.get("stored_count", 0),
                "failed_chunks": storage_result.get("failed_count", 0)
            }
            
            logger.info(f"单个PDF文件导入完成: {result}")
            return result
            
        except Exception as e:
            logger.error(f"导入单个PDF文件失败: {e}")
            return {
                "success": False,
                "error": str(e),
                "file_path": pdf_path
            }
    
    def search_knowledge(self, query: str, limit: int = 3, similarity_threshold: float = 0.7) -> List[Dict[str, Any]]:
        """
        在知识库中搜索相关内容
        
        Args:
            query: 查询文本
            limit: 返回结果数量限制
            similarity_threshold: 相似度阈值
            
        Returns:
            搜索结果列表
        """
        try:
            logger.info(f"搜索知识库: '{query[:50]}...'")
            
            results = self.knowledge_base.search_similar_content(
                query=query,
                limit=limit,
                similarity_threshold=similarity_threshold
            )
            
            logger.info(f"知识库搜索完成: 返回 {len(results)} 个结果")
            return results
            
        except Exception as e:
            logger.error(f"知识库搜索失败: {e}")
            return []
    
    def get_knowledge_base_stats(self) -> Dict[str, Any]:
        """
        获取知识库统计信息
        
        Returns:
            统计信息
        """
        try:
            stats = self.knowledge_base.get_collection_stats()
            logger.info(f"知识库统计信息: {stats}")
            return stats
        except Exception as e:
            logger.error(f"获取知识库统计信息失败: {e}")
            return {"error": str(e)}
    
    def clear_knowledge_base(self) -> bool:
        """
        清空知识库
        
        Returns:
            bool: 清空是否成功
        """
        try:
            result = self.knowledge_base.clear_collection()
            logger.info(f"知识库清空结果: {result}")
            return result
        except Exception as e:
            logger.error(f"清空知识库失败: {e}")
            return False
    
    def close(self):
        """关闭服务连接"""
        try:
            if hasattr(self, 'knowledge_base'):
                self.knowledge_base.close()
            logger.info("PDF导入服务连接已关闭")
        except Exception as e:
            logger.error(f"关闭PDF导入服务失败: {e}")


def create_pdf_import_service(chunk_size: int = 1000, chunk_overlap: int = 200) -> PDFImportService:
    """
    创建PDF导入服务实例
    
    Args:
        chunk_size: 文本块大小
        chunk_overlap: 文本块重叠大小
        
    Returns:
        PDFImportService实例
    """
    return PDFImportService(chunk_size=chunk_size, chunk_overlap=chunk_overlap)
